package com.woniuxy.consumer.listener.dlx;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class DlxQueueListener {

    @RabbitListener(queues = "normal-queue")
    public void handlerMsg(String msg, Channel channel, Message message) throws IOException {

        try {
            // 模拟异常
            //int i = 1/0;
            // 消费者手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            // 获取重投标记
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (redelivered){
                //拒绝重投
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                System.out.println("重投消息消费也是失败，拒绝消息！");
            } else {
                //重投
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                System.out.println("消息消费失败，进行重投");
            }
        }
    }
}
